package com.erick.springcloud.gateway;

import com.ecwid.consul.v1.ConsulClient;
import com.erick.springcloud.gateway.consulregister.GatewayRegister;
import com.erick.springcloud.gateway.redislimiter.SystemRedisRateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.validation.Validator;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Description :
 * @Param
 * @author : Erick
 * @version : 1.0
 * @Date : 2018-10-26
 */
@SpringBootApplication
public class SpringcloudGatewayApplication {

    @Autowired(required = false)
    private TtlScheduler ttlScheduler;

    @Bean
    public GatewayRegister consulServiceRegistry(ConsulClient consulClient, ConsulDiscoveryProperties properties,
                                                 HeartbeatProperties heartbeatProperties) {
        return new GatewayRegister(consulClient, properties, ttlScheduler, heartbeatProperties);
    }

    /**
     * @Description :不通过配置文件采用配置的方式实现路由转发
     * @Param [args]
     * @author : Erick
     * @version : 1.0
     * @Date : 2018-10-26
     */
//    @Bean
//    public RouteLocator customRouteLocator(RouteLocatorBuilder builder){
//        return builder.routes()
//                .route(r->r.path("/gateway/baidu")
//                .uri("http://baidu.com"))
//                .build();
//    }

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudGatewayApplication.class, args);
    }

    @Bean
    KeyResolver sysKeyResolver(){
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("sys"));
    }

    @Bean
    @Primary
    SystemRedisRateLimiter systemRedisRateLimiter(
            ReactiveRedisTemplate<String, String> redisTemplate,
            @Qualifier(SystemRedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript<List<Long>> script,
            Validator validator){
        return new SystemRedisRateLimiter(redisTemplate , script , validator);
    }
}
